<?
class Section{
    
    static function Get($id, $sort = array(), $fields = "*"){
        $filter = array('id' => $id, DB_LOGIC_OR.":section_id"=>$id);
        return Section::GetList($filter, $sort, $fields);
    }
    
    static function GetListAsTree($filter = array(), $sort = array(), $fields = "*", $limit = false){
        $data = Section::GetList($filter, $sort, $fields, $limit);
        return Tree($data, 'id', 'section_id', 'sections', true);
    }
    
    static function GetList($filter = array(), $sort = array(), $fields = "*", $limit = false){
        $filter['is_section'] = 1;
        BDS::Init();
        $result = BDSElement::GetList($filter, $sort, $fields, $limit);
        if(!$result){
            return false;
        }
        $result = $result->GetList();
        foreach($result as $i => $section){
            $count = BDSElement::GetList(array('section_id' => $section['id'], 'is_section' => N, DB_LOGIC_OR.":section_id" => $section['id']), array(), array('count(id)' =>'count'))->fetchObj()->count;
            $result[$i]['count'] = (int)$count;
            $fldObj = FLDFields::GetList(array('block_id' => $section['block_id'], 'is_section' => 1));
            while($field = $fldObj->fetch()){
                $result[$i]['fields'][$field['code']] = $field;
                $valObj = FLDValues::GetList(array('element_id' => $section['id'], 'field_id' => $field['id']));
                if($field['is_multi']){
                    while($value = $valObj->fetch()){
                        $result[$i]['fields'][$field['code']]['value'][] = $value['value'];
                    }
                }else{
                    $value = $valObj->fetch();
                    $result[$i]['fields'][$field['code']]['value'] = $value['value'];
                }
            }
        }
        return $result; 
    }
    
}